package wx

import (
	"app/pkg/config"
	httpUtil "app/pkg/http"
	"encoding/json"
	"fmt"
)

const (
	AccessTokenKey = "access_token_key"
)

type AccessTokenReply struct {
	AccessToken string `json:"access_token"`
	ExpiresIn   int    `json:"expires_in"`
}

type PhoneInfo struct {
	PhoneNumber     string `json:"phoneNumber"`
	PurePhoneNumber string `json:"purePhoneNumber"`
}

type Jscode2sessionReply struct {
	Openid  string `json:"openid"`
	Errcode int    `json:"errcode"`
	Errmsg  string `json:"errmsg"`
}

func Jscode2session(code string) (openid string, err error) {
	res, err := httpUtil.Get(fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", config.Config.Wx.Appid, config.Config.Wx.Secret, code), map[string]string{}, 10)
	if err != nil {
		return
	}
	reply := Jscode2sessionReply{}
	err = json.Unmarshal(res, &reply)
	if err != nil {
		return
	}
	if reply.Errcode != 0 {
		err = fmt.Errorf(reply.Errmsg)
		return
	}
	openid = reply.Openid
	return
}

type getPhoneNumberReply struct {
	Errcode   int       `json:"errcode"`
	Errmsg    string    `json:"errmsg"`
	PhoneInfo PhoneInfo `json:"phone_info"`
}

func GetPhoneNumber(code string) (phone string, err error) {
	token, err := GetAccessToken()
	if err != nil {
		return
	}
	res, err := httpUtil.Post(fmt.Sprintf("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s", token), map[string]string{"code": code}, map[string]string{}, 10)
	if err != nil {
		return
	}
	phoneReply := getPhoneNumberReply{}
	err = json.Unmarshal(res, &phoneReply)
	if err != nil {
		return
	}
	if phoneReply.Errcode != 0 {
		err = fmt.Errorf(phoneReply.Errmsg)
		return
	}
	phone = phoneReply.PhoneInfo.PurePhoneNumber
	return
}

func GetAccessToken() (token string, err error) {
	// token, err = redis.String(db.DB.RedisPool.Get().Do("GET", AccessTokenKey))
	// if err != nil {
	at, err1 := getAccessToken()
	if err1 != nil {
		return "", err1
	}
	// db.DB.RedisPool.Get().Do("SET", AccessTokenKey, at.AccessToken, "ex", at.ExpiresIn)
	token = at.AccessToken
	// }
	return
}

func getAccessToken() (at AccessTokenReply, err error) {
	res, err := httpUtil.Get(fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", config.Config.Wx.Appid, config.Config.Wx.Secret), map[string]string{}, 10)
	if err != nil {
		return
	}
	err = json.Unmarshal(res, &at)
	return
}
